global.linkkey_Clients_ws = {}
global.id_Clients_linkkey = {}
global.linkkey_Clients_id = {}
global.gps = {}
global.GSpace={}

const { json } = require('body-parser')
var events = require('events');
global.eventEmitter = new events.EventEmitter();
exports.linksuccess = (ws, req) => {
    //  console.log("客户端数量：",req)
    let link_key = ""
    for (let i = 0; i < req.rawHeaders.length; i++) {
        if (req.rawHeaders[i] == "Sec-WebSocket-Key") {
            link_key = req.rawHeaders[i + 1]
            break
        }
    }
    linkkey_Clients_ws[link_key] = {
        ws:ws,
        dataType:"json"
    }
    this.send_response_by_ws(ws,"link.success", {  "code": 200, "msg": "你连接成功了" })
    this.printLength();
    return link_key
}

/**
 *  通过ws推送消息
 * @param {接受者websocket} ws 
 * @param {消息cmd} cmd 
 * @param {信息object} obj 
 */
exports.send_response_by_ws = (ws,cmd, obj) => {
    if (ws != null) {
        obj.c = cmd
        ws.send(JSON.stringify(obj))
    }
}

/**
 *  推送消息
 * @param {接受者id} id 
 * @param {消息cmd} cmd 
 * @param {信息object} obj 
 */
exports.send_response = (id,cmd,obj) => {
    let link_key = id_Clients_linkkey[id]
    //  console.log("send:", id, msg,ws)
    if (link_key != null) {
        let info = linkkey_Clients_ws[link_key]
        if (info != null && info.ws!=null) {
            obj.c = cmd
           // console.log(JSON.stringify(obj))
            info.ws.send(JSON.stringify(obj))
        }
    }
}

/**
 *  推送消息
 * @param {接受者id} id 
 * @param {字符串} msg 
 */
exports.send_msg = (id, msg) => {
    let link_key = id_Clients_linkkey[id]
    //  console.log("send:", id, msg)
    if (link_key != null) {
        let info = linkkey_Clients_ws[link_key]
        if (info != null && info.ws!=null){
            try {
                info.ws.send(msg)
            } catch (error) {
                console.log("send",id,msg,error)
            }
          
        }
    }
}

/**
 * 打印当前连接数量
 */
exports.printLength = () => {
    let length0 = Object.keys(linkkey_Clients_ws).length
    let length1 = Object.keys(id_Clients_linkkey).length
    let length2 = Object.keys(linkkey_Clients_id).length
    console.log("当前连接用户量:", length0, "_", length1, "_", length2)
}

/**
 * 获取空间信息
 * @param {空间类型：大厅、房间} sptype 
 * @returns 返回空间信息
 */
exports.getSpace =function(sptype)
{
  return global.GSpace[sptype]
}

/**
 * 获取玩家所在空间的信息
 * @param {用户id} pid 
 * @param {空间类型} sptype 
 * @returns 玩家列表
 */

exports.getPlayersBySpace = function(pid,sptype)
{
  let spaceTab = this.getSpace(sptype)
  if(spaceTab)
  {
    for (let spaceName in spaceTab) {
        let space = spaceTab[spaceName]
        if (space != null) {
            if (space.players.includes(pid)) {
                return space.players
            }
            break
        }
    }
  }
  return null;
}

/**
 * 根据类型、名称获取空间信息
 */
exports.getSpaceByTypeAndName = function (type, name) {
    var result = null
    let space = this.getSpace(type);
    if (space)
    {
        result = space[name]
    }
    return result
}

/**
 * 根据类型、名称获取所有玩家ids,比如说查找大堂、查找房间.
 */
exports.getPlayersByType = function (type, name) {
    let space =  this.getSpaceByTypeAndName(type,name)
    let reslut = null
    if (space)
    {
        result = space[name]
    }
    // console.log("findPlayers",type,result)
    if (result == null) return [];
    return result.players
}

/**
 * 
 * @param {我的id} id 
 * @returns 当前所在的位置的所有玩家
 */
exports.findPlayers = function (id) {
    let temp = gps[id]   
    if (temp != null) {
        return this.getPlayersByType(temp.placeType, temp.placeName);
    }
    return []
}

/**
 * 移除玩家信息
 * @param {用户id} id 
 */
exports.removePlayerInSpace = function (id) {
    let temp = gps[id]
    if (temp != null) {
        let space = this.getSpace(temp.placeType)
        if(space)
        {
            let result = space[temp.placeName]
            if (result != null) {
                let players = result.players
                for (let i = 0; i < players.length; i++) {
                    if (players[i] == id) {
                        players.splice(i, 1);
                        i--;
                    }
                }
            }
        }
    }
    delete gps[id]
}

/**
 * 玩家退出某个地方
 *  * @param {玩家id} id 
 */
exports.GPS_Exit = function (id) {
    removePlayerInSpace(id)
}

/**
 * 玩家进入某个地方
 * @param {用户id} id 
 * @param {空间类型} _type 
 * @param {空间名称} _name 
 */
exports.GPS_Join = function (id, _type, _name = "") {
    gps[id] = {
        placeType: _type,
        placeName: _name
    }

    let tab = null
    if (!global.GSpace[_type])
    {
        global.GSpace[_type] = {}
    }
    tab = global.GSpace[_type]
    if (tab[_name] == undefined) {           
        tab[_name] = {
            name: _name,
            players: [id]
        }
    }
    else {
        //todo 加入大厅\房间
        if (tab[_name].players.includes(id) == false) {
            //已经在该大厅，就抛弃数据.
            tab[_name].players.push(id)
        }
    }
}


/**
 * 玩家断开连接
 * @param {玩家socket} linkkey 
 */
exports.closeLink = function (linkkey) {
    var id = linkkey_Clients_id[linkkey]
    var info = linkkey_Clients_ws[linkkey]
    console.log("closeLink", id, linkkey)
    if (id) {
        eventEmitter.emit('closeLink', id);
        console.log('close connection:', id)

        delete id_Clients_linkkey[id];
        this.removePlayerInSpace(id)
        delete gps[id]
    }
    delete linkkey_Clients_ws[linkkey];
    delete linkkey_Clients_id[linkkey];
    this.printLength();
}

exports.newLink = function (ws) {

}